WordPress主题开发笔记

235次阅读
没有评论

共计 6547 个字符,预计需要花费 17 分钟才能阅读完成。

本地开发环境

下载并安装 Local:https://localwp.com/

打开 Local,点击「+ Create a new site],输入网站名称(例如:test),点击「Continue」->「Continue」,输入用户名、密码、邮箱,点击「Add Site」,稍等片刻,网站就安装完成了。

点击「Open site」,即可打开网站。

可能出现打不开网站的情况。如果之前安装过 VMware Workstation,端口 443 会存在冲突。打开「服务」应用,找到「VMware Workstation Server」,右键「属性],启动类型改为「手动」。

创建新主题

在网站上右键「Go to site folder」,打开网站文件路径,进到test/app/public/wp-content/themes,新建文件夹(例如:mytheme),进入 mytheme/,新建文件 index.phpstyle.css,所有主题都需要这两个文件。

在文件 style.css 写入:

/*
    Theme Name: My Theme
    Author: GAGA
    Version: 0.1
*/

在文件 index.php 写入:

<?php
    while(have_posts()){the_post(); ?>
        <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
        <?php the_content(); ?>
        <hr>
    <?php }
?>
  • have_posts() 检查当前页面是否有文章
  • the_post() 显示全部文章
  • the_permalink() 显示永久链接 /URL 地址
  • the_title() 显示标题
  • the_content() 显示内容
  • the_excerpt() 显示文章摘要
  • get_the_excerpt() 获取文章摘要

可以在主题目录创建一张图片重命名为 screenshot.png 或者screenshot.jpg,WordPress 会自动读取该图片为主题的缩略图。

文章和页面

在主题目录创建文件single.phppage.php,分别是「文章」详情页模版文件和「页面」详情页模版文件。

在文件 single.php 和 page.php 写入:

<?php
    while(have_posts()){the_post(); ?>
        <h2><?php the_title(); ?></h2>
        <?php the_content(); ?>
    <?php }
?>

自定义页面模板

在主题目录创建文件page-event.php,作为 event 页面的模版文件。

页眉和页脚

在主题目录创建文件header.phpfooter.php,分别用于显示网站页眉和页脚。

在文件 header.php 写入:

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
    <h1> 这里是页眉 </h1>

在文件 footer.php 写入:

<p> 这里是页脚 </p>
<?php wp_footer(); ?>
</body>
</html>
  • wp_head() 头部输出函数,很多插件依赖这个函数
  • wp_footer() 尾部输出函数,很多插件依赖这个函数
  • language_attributes() 显示 html 标签的语言属性
  • bloginfo() 显示站点信息
  • body_class() 用来给 body 标签添加类

文件 index.php 修改为:

<?php
    get_header();
    while(have_posts()){the_post(); ?>
        <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
        <?php the_content(); ?>
        <hr>
    <?php }
    get_footer();
?>

文件 single.php 和 page.php 修改为:

<?php
    get_header();
    while(have_posts()){the_post(); ?>
        <h2><?php the_title(); ?></h2>
        <?php the_content(); ?>
    <?php }
    get_footer();
?>
  • get_header() 加载 header.php 文件
  • get_footer() 加载 footer.php 文件

模版函数文件

在主题目录创建文件functions.php,这个是 WordPress 保留的函数文件,它专门用于添加各种自定义函数代码。

<?php
// 定义函数
function my_files() {wp_enqueue_style('my_main_sytles', get_theme_file_uri('/static/css/main.css'));
    wp_enqueue_script('my_main_js', get_theme_file_uri('/static/js/index.js'));
}
// 绑定动作,把函数 my_files 挂载到 wp_enqueue_scripts 下面
add_action('wp_enqueue_scripts', 'my_files');
  • wp_enqueue_scripts 钩子用于前端排队脚本和样式,如果是在后台调用,使用 admin_enqueue_scripts 钩子
  • wp_enqueue_style() 用于引入样式文件
  • get_theme_file_uri() 获取主题目录,如果没有使用子主题,使用 get_template_directory_uri() 可获得更好性能
  • wp_enqueue_script() 用于引入 js 文件

添加主题功能

function my_features() {add_theme_support('title-tag');
    register_nav_menu('headerMenu', 'Header Menu');
    register_nav_menu('footerMenu', 'Footer Menu');
}
add_action('after_setup_theme', 'my_features');
  • add_theme_support() 自动生成页面标题信息(title-tag),如果想通过 hook 调用,则必须使用 after_setup_theme 这个钩子
  • register_nav_menu() 注册一个菜单
  • after_setup_theme 钩子在主题被初始化之后在每个页面加载期间被调用

主页显示

1、设置 -> 阅读 -> 您的主页显示:您的最新文章

模板文件的调用顺序:front-page.php > home.php > index.php

2、设置 -> 阅读 -> 您的主页显示:一个静态页面

页面为“主页”,模板文件的调用顺序:front-page.php > page.php > index.php

页面为“文章页”,模板文件的调用顺序:home.php -> index.php

模板文件 index.php 能不用就不用。如果打算只设置为“您的最新文章”,可以不用模板文件 front-page.php,使用 home.php 即可;如果打算设置为“一个静态页面”,建议“主页”使用模板文件 front-page.php,不要使用模板文件 page.php。

存档页

archive.php:默认存档页模版文件。

主题模板文件

主模板

  • index.php
  • home.php
  • single.php
  • page.php
  • archive.php
  • search.php
  • 404.php
  • comment.php

二级模板

  • front-page.php
  • author.php
    date.php
    tag.php
    category.php
    taxonomy.php
  • attachment.php
    single-post.php

分部模板

  • 页头 header.php -> get_header();
  • 页脚 footer.php -> get_footer();
  • 侧边栏 sidebar.php -> get_sidebar();
  • 搜索框 searchform.php -> get_search_form();
  • 评论 comments.php -> comments_template();
  • 自定义模板 xxx.php -> get_template_part();

可变模板

  • tag-$id.php
    tag-1.php
    tag-2.php
  • tag-$slug.php
    tag-ios.php
    tag-android.php

一些常见函数

is_category() 判断当前页面是否为分类页面
is_author() 判断当前页面是否为作者页面
is_admin() 判断当前页面是否为管理页面
is_post_type_archive() 判断当前页面是否为文章类型列表页
is_main_query() 判断当前查询是否为主查询
the_author_posts_link() 获取当前作者文章归档页面链接
the_archive_title() 根据查询的对象显示归档标题
the_archive_description() 返回归档的相关描述
the_time() 时间函数。the_time(‘Y-m-d’)显示为 2022-06-30
site_url() 返回 WordPress 安装路径
home_url() 返回首页地址
has_excerpt() 通过 id 判断文章是否设置了摘要
paginate_links() 获取页面分页链接
single_cat_title() 用于在分类页输出分类标题
get_the_ID() 获取当前 id
get_the_category_list() 获取文章所有分类列表
get_permalink() 获取当前文章的链接,get_permalink(99)获取指定 id 的文章或页面链接
get_pages() 获取已定义页面列表,get_pages(array(‘child_of’ => 2))
get_the_content() 获取文章内容
get_post_type() 根据文章 id 获取文章类型
get_post_type_archive_link() 获取指定文章类型的文章列表链接
get_query_var() 查询当前文章的分类及分页
wp_get_post_parent_id() 获取父级 id
wp_list_pages() 显示页面列表,wp_list_pages(array(‘title_li’ => NULL,’child_of’ => 2))
wp_nav_menu() 引用菜单,wp_nav_menu(array(‘theme_location’ => ‘headerMenu’))
wp_trim_words() 截取字符串,wp_trim_words(get_the_content(), 20)

自定义查询 WP_Query

<?php
// WP_Query 所使用的参数
$args = array(
    'posts_per_page' => 3, //- 1 一次返回满足查询的所有内容
    'post_type' => 'post',
    'orderby' => 'title',
    'order' => 'ASC',
    'meta_query' => array(
        array(
            'key' => '字段名',
            'compare' => '>=',
            'value' => date('Ymd'),
            'type' => 'numeric'
        )
    )
);
// 调用 WP_Query 新建文章查询
$the_query = new WP_Query($args);
while ($the_query->have_posts()) {$the_query->the_post();
    the_title();
    the_excerpt();}
wp_reset_postdata(); // 重置 WordPress 查询
?>

自定义文章类型

创建一个新的自定义文章类型需要使用 register_post_type 函数来注册,在主题的 functions.php 文件下调用该函数即可。

这里推荐另一种方法,先在 wp-content/ 目录下新建文件夹:mu-plugins,即必须使用(must-use)的插件。进入文件夹,新建文件(例如:my_post_types.php),写入:

<?php
function my_post_types() {
    register_post_type('event', array(
        'show_in_rest' => true, // 支持古腾堡编辑器
        'supports' => array('title', 'editor', 'excerpt'),
        'rewrite' => array('slug' => 'events'),
        'has_archive' => true,
        'public' => true,
        'labels' => array(
            'name' => 'Events',
            'add_new_item' => 'Add New Event',
            'edit_item' => 'Edit Events',
            'all_items' => 'All Events',
            'singular_name' => 'Event'
        ),
        'menu_icon' => 'dashicons-calendar'));
}
add_action('init', 'my_post_types');

在主题目录创建文件single-event.php,作为自定义文章类型(这里以 event 举例)详情页模版文件;新建文件archive-event.php,作为自定义文章类型存档页模版文件。

自定义字段

可以考虑使用插件:Advanced Custom Fields,允许添加多种形式的自定义字段类型。

插件安装启用后,可以使用 the_field() 和 get_field() 这两个函数。前者是直接输出字段值,后者是获取字段值以供其他函数调用。

自定义查询分页

一般来说,WordPress 分页只能在默认查询中使用,想要自定义查询分页,需要做些工作。

<?php
$args = array('paged' => get_query_var('paged', 1),
    'post_type' => 'post',
    'meta_query' => array(
        array(
            'key' => '字段名',
            'compare' => '>=',
            'value' => date('Ymd'),
            'type' => 'numeric'
        )
    )
);
// 调用 WP_Query 新建文章查询
$the_query = new WP_Query($args);
while ($the_query->have_posts()) {$the_query->the_post();
    the_title();
    the_excerpt();}
wp_reset_postdata(); // 重置 WordPress 查询

echo paginate_links(array('total' => $the_query->max_num_pages));
?>

hook 钩子

pre_get_post:修改主查询

function my_adjust_queries() {if (!is_admin() AND is_post_type_archive('post' AND $query->is_main_query())) {$query->set('meta_key', 'event_date');
        $query->set('orderby', 'meta_value_num');
        $query->set('order', 'ASC');
        $query->set('meta_query', array(
            array(
                'key' => 'event_date',
                'compare' => '>=',
                'value' => date(format('Ymd')),
                'type' => 'numeric'
            )
        ));
    }
}
add_action('pre_get_post', 'my_adjust_queries');

正文完
 0
阿伯手记
版权声明:本站原创文章,由 阿伯手记 于2023-08-18发表,共计6547字。
转载说明:本站原创内容,除特殊说明外,均基于 CC BY-NC-SA 4.0 协议发布,转载须注明出处与链接。
评论(没有评论)
验证码

阿伯手记

阿伯手记
阿伯手记
喜欢编程,头发渐稀;成长路上,宝藏满地
文章数
766
评论数
204
阅读量
450060
今日一言
-「
热门文章
职场救急!AI请假话术生成器:1秒定制高通过率理由

职场救急!AI请假话术生成器:1秒定制高通过率理由

超级借口 不好开口?借口交给我!智能生成工作请假、上学请假、饭局爽约、约会拒绝、邀约推辞、万能借口等各种借口理...
夸克网盘快传助手提高非VIP下载速度

夸克网盘快传助手提高非VIP下载速度

夸克网盘限速这个大家都知道,不开会员差不多限速在几百 K。那有没有办法在合法合规途径加速下载夸克网盘呢?这里推...
国内已部署DeepSeek模型第三方列表 免费满血版联网搜索

国内已部署DeepSeek模型第三方列表 免费满血版联网搜索

本文收集了目前国内已部署 DeepSeek 模型的第三方列表,个个都是免费不限次数的满血版 DeepSeek,...
巴别英语:用美剧和TED演讲轻松提升英语听力与口语

巴别英语:用美剧和TED演讲轻松提升英语听力与口语

还在为枯燥的英语学习而烦恼吗?巴别英语通过创新的美剧学习模式,让英语学习变得生动有趣。平台提供海量美剧和 TE...
Chinese Name Generator 在线中文姓名生成器

Chinese Name Generator 在线中文姓名生成器

Chinese Name Generator 是一款在线中文姓名生成器,可在几秒内生成符合个人需求的中文名字。...
TVAPP:开源电视盒子资源库,一键打造家庭影院

TVAPP:开源电视盒子资源库,一键打造家庭影院

导语 TVAPP 是一个专为 Android TV 电视盒子用户打造的开源影音资源库,集成了影视、直播、游戏等...
2025年12月 每日精选

2025年12月 每日精选

关于每日精选栏目 发现一些不错的资源,点击 这里 快速投稿。 12 月 26 日 .ax 顶级域 目前全球唯一...
最新评论
15220202929 15220202929 怎么用
八对 八对 麻烦大佬更新下【堆新】的友链站名:八对星星描述:极目星视穹苍无界•足履行者大地有疆链接:https://8dui.com图标:https://cf.8dui.com/logo.webp横标:https://cf.8dui.com/logo-w.webp订阅:https://8dui.com/rss.xml
三毛笔记 三毛笔记 已添加
DUINEW DUINEW 已添加贵站,期待贵站友链~博客名称:堆新博客地址:https://duinew.com/博客描述:堆新堆新,引力向新!——堆新(DUINEW)博客头像:https://d.duinew.com/logo.webp横版头像:https://d.duinew.com/logo-w.webp博客订阅:https://duinew.com/rss.xml
hedp hedp 没看懂
bingo bingo 直接生成就可以啦,也可以添加一些选项
满心 满心 申请更新下友联信息,原名:满心记,现名:周天记原域名:qq.mba,现域名:zhoutian.com描述:我在人间混日子
开业吉日 开业吉日 没看明白这个怎么用
开业吉日 开业吉日 beddystories 这个网站太赞了,收藏
热评文章
夸克网盘快传助手提高非VIP下载速度

夸克网盘快传助手提高非VIP下载速度

夸克网盘限速这个大家都知道,不开会员差不多限速在几百 K。那有没有办法在合法合规途径加速下载夸克网盘呢?这里推...
清华大学官方免费DeepSeek教程

清华大学官方免费DeepSeek教程

AI 领域近期最引人注目的焦点当属 DeepSeek,这款由中国创新企业深度求索研发的人工智能工具,正以开放源...
Short-Link 免费开源短网址程序,基于Fastify、Vercel和Supabase构建

Short-Link 免费开源短网址程序,基于Fastify、Vercel和Supabase构建

Short-Link 是一款基于 Fastify、Vercel 和 Supabase 构建的 URL 缩短服务...
国内已部署DeepSeek模型第三方列表 免费满血版联网搜索

国内已部署DeepSeek模型第三方列表 免费满血版联网搜索

本文收集了目前国内已部署 DeepSeek 模型的第三方列表,个个都是免费不限次数的满血版 DeepSeek,...
Chinese Name Generator 在线中文姓名生成器

Chinese Name Generator 在线中文姓名生成器

Chinese Name Generator 是一款在线中文姓名生成器,可在几秒内生成符合个人需求的中文名字。...
BeddyStories 完全免费儿童睡前故事库,让孩子随时随地入睡更轻松

BeddyStories 完全免费儿童睡前故事库,让孩子随时随地入睡更轻松

BeddyStories 是一个致力于为儿童提供优质睡前故事的在线平台,用户可以在这里找到来自世界各地的经典故...
DrawLink:一键生成链接视觉卡片,提升分享点击率

DrawLink:一键生成链接视觉卡片,提升分享点击率

小贴士 :此站或已变迁,但探索不止步。我们已为您备好「类似网站」精选合集,相信其中的发现同样能为您带来惊喜。